package jlb.andriva;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import jlb.andriva.wrappers.HttpTask;
import jlb.andriva.wrappers.Rates;
import jlb.andriva.wrappers.Util;

public class RatesActivity extends Fragment {

    private View rootView;
    private Element rootElem = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_rates, container, false);

        if(rootElem == null){
        	if(LoginActivity.mTestMode == false){
	            RatesTask mRatesTask = new RatesTask();
	            mRatesTask.execute(getString(R.string.rates_url));
        	}
        	else{
        		Document doc = org.jsoup.Jsoup.parse(Util.getRawContent(rootView.getContext(), R.raw.rates));
                rootElem = doc.select("table[border=0]").first();
                if(rootElem != null){
                    paintResults();
                }
        	}
        }
        else{
            //Paint cache results
            paintResults();
        }

        return rootView;
    }

    private class RatesTask extends HttpTask {
        @Override
        protected void onPostExecute(final String result) {
            if (result != null) {
                Document doc = org.jsoup.Jsoup.parse(result);
                rootElem = doc.select("table[border=0]").first();
                if(rootElem != null){
                    paintResults();
                }
            }
        }
    }

    private void paintResults(){
        ViewGenerator vg = new ViewGenerator();
        vg.execute(rootView.getContext());
    	
    	/*Rates rates = new Rates(rootElem);
        LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.rates_list);
        ll.addView(rates.getView(rootView.getContext()));*/
    }

    private class ViewGenerator extends AsyncTask<Context, Void, LinearLayout> {

        @Override
        protected LinearLayout doInBackground(Context... contexts) {
            Rates rates = new Rates(rootElem);
            return rates.getView(contexts[0]);
        }

        @Override
        protected void onPostExecute(final LinearLayout result) {
            LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.rates_list);
            ll.addView(result);
        }
    }
}